package com.family.instagram;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.wu.family.config.UserInfo;

import android.R.bool;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.webkit.CacheManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * 
 * @author 	goodluckze
 * @note 	Instagram登录相关
 */
public class InstagramEngine {
	public static InstagramEngine 	instance;
	public static String 			CLIENT_ID 		= "cfa07a1aad354477a0cc888a8266edee";
	public static String 			CLIENT_SECRET 	= "97fc4a5719f7440690f892e2f85aa882";
	public static String 			REDIRECT_URl 	= "http://www.familyday.com.cn";
	
	public static String 			URL_ACCESSTOKEN = 
		"https://instagram.com/oauth/authorize?response_type=token&redirect_uri=http://www.familyday.com.cn&scope=basic+comments+relationships+likes&client_id=cfa07a1aad354477a0cc888a8266edee";
	public static String 			URL_USERINFO	= 
		"https://api.instagram.com/v1/users/self/?access_token=";
	public static String 			URL_LOGIN2FAMILY= 
		"http://www.familyday.com.cn/dapi/do.php?ac=login&logintype=instagram&name=%1$s&instagram_uid=%2$s&instagram_token=%3$s&avatar=%4$s";
	public static String 			URL_FEEDLIST= 
		"https://api.instagram.com/v1/users/self/feed?access_token=%1$s&count=%2$s&max_id=%3$s";
	
	private static String 			mToken;
	private static UserInfo			mUser;
	private static MyOnClickListener buttonClickListener;
	private static InstagramCallBack callBack;
	private boolean 				isRun;
	
	public static InstagramEngine getInstance()
	{
		if( instance == null ){
			instance = new InstagramEngine();
			buttonClickListener = instance.new MyOnClickListener();
		}
		return instance;
	}
	public void initInfo(String pToken , UserInfo pUserInfo)
	{
		// 用缓存数据初始化信息
		mToken 	= pToken;
		mUser 	= pUserInfo;
	}
	public void getUserPhoto(final String token,final String count,final String maxId,final InstagramDataCallBack pCall)
	{
		System.out.println("token---getUserPhoto:" + token);
		// 参数1 token 参数2 一次返回多少条 参数3 查更多数据时填入已有数据的最后一条数据的id，如果是第一次调用，则填""
		if( isRun ){
			pCall.onGetFeedInfo(null);
		}
		new AsyncTask<String, String, String>() {
			
			protected void onPreExecute() {
				isRun = true;
			};
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				String respon = NetHelper.getResponByHttpClient
				(URL_FEEDLIST,token ,count, maxId);
				return respon;
			}
			
			protected void onPostExecute(String result) {
				isRun = false;
				try {
					InstagramImgObj[] imgArray 	= null ;
					JSONObject object 	= new JSONObject(result);
					JSONArray	array   = object.getJSONArray("data");
					imgArray 			= new InstagramImgObj[array.length()];
					JSONObject	tempObj;
					for (int i = 0; i < array.length(); i++) {
						tempObj 			= array.getJSONObject(i);
						imgArray[i]			= new InstagramImgObj();
						imgArray[i].type 	= tempObj.optString("type");
						imgArray[i].id 		= tempObj.optString("id");
						imgArray[i].time 	= tempObj.optString("created_time");
						//这段字段有可能是null，也可能是JSON对象字段，所以加入处理
						try {
							imgArray[i].caption = tempObj.getJSONObject("caption").optString("text");
						} catch (Exception e) {
							e.printStackTrace();
							imgArray[i].caption = "";
						}
						
						try {
							imgArray[i].username = tempObj.getJSONObject("user").optString("username");
						} catch (Exception e) {
							e.printStackTrace();
							imgArray[i].username = "";
						}
						
						imgArray[i].imgUrl_thumbnail  = tempObj.getJSONObject("images").
												getJSONObject("thumbnail").optString("url");
						imgArray[i].imgUrl_low  = tempObj.getJSONObject("images").
												getJSONObject("low_resolution").optString("url");
						imgArray[i].imgUrl_standard  = tempObj.getJSONObject("images").
												getJSONObject("standard_resolution").optString("url");
						if( imgArray[i].type.equals("video") )
						{
							imgArray[i].videoUrl = tempObj.getJSONObject("videos").
													getJSONObject("standard_resolution").optString("url");
						}
						
					}
					pCall.onGetFeedInfo(imgArray);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
			};
		}.execute("");
	}
	public static String getToken()
	{
		return mToken;
	}
	public static void setCallBack(InstagramCallBack pCallBack)
	{
		callBack = pCallBack;
	}
	public static void loginOutInstagram(Context mContext)
	{
		
		cleanCache(mContext);
		if (callBack != null) {
			callBack.clearCache();
		}
	}
	private UserInfo getUserInfo()
	{
		return mUser;
	}
	
	public static void loginInstagram( Context context, WebView webView,InstagramCallBack callBack)
	{	
		setCallBack(callBack);
		if( callBack.isLogin() ){
			buttonClickListener.mContext = context;
			buttonClickListener.mWebView = webView;
			new AlertDialog.Builder(context).setMessage("检测到已经有登录的Instagram帐号，需要清空缓存吗？")
			.setPositiveButton("需要", buttonClickListener).setNegativeButton("返回", buttonClickListener).create().show();
		}else {
			webView.getSettings().setJavaScriptEnabled(true);
			webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  // 不使用浏览器的缓存
			webView.loadUrl(URL_ACCESSTOKEN);
			webView.setWebViewClient(client);
		}
		
	}
	
	public static void cleanCache(Context context){
		File file = CacheManager.getCacheFileBaseDir();  
		   if (file != null && file.exists() && file.isDirectory()) {  
		    for (File item : file.listFiles()) {  
		     item.delete();  
		    }  
		    file.delete();  
		   }  
		  
		  context.deleteDatabase("webview.db");  
		  context.deleteDatabase("webviewCache.db");  
		  
		  CookieSyncManager.createInstance(context); 
		  CookieManager cookieManager = CookieManager.getInstance();
		  cookieManager.removeAllCookie();
		  
		  // 也删掉保存的Instagram标志和Token。成武原本的程序框架在退出时没有清空UserInfo的配置，
		  	//导致第二次登录不同方式或者不同帐号时，有些异常
		  com.wu.family.config.UserInfo userInfo = 
			  com.wu.family.config.UserInfo.getInstance(context);
		  userInfo.setInstagramToken("");
		  userInfo.setIsInstagramBind("0");
		  
	}
	private static void onReturn(String result){
		try {
			JSONObject object 	= new JSONObject(result);
			object 				= object.getJSONObject("data");
			UserInfo info 		= new UserInfo();
			
			info.id				= object.optString("id");
			info.username		= object.optString("username");
			info.full_name		= object.optString("full_name");
			info.profile_picture = object.optString("profile_picture");
			info.bio 			= object.optString("bio");
			info.website 		= object.optString("website");
			
			object				= object.getJSONObject("counts");
			info.counts_media 	= object.optString("media");
			info.counts_follows 	= object.optString("follows");
			info.counts_followed_by 	= object.optString("followed_by");
			
			mUser = info;
			
			login2Family();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	public static ArrayList<Map<String, Object>> instagramData2WaterFallData( InstagramImgObj[] array )
	{
		ArrayList<Map<String, Object>> imageList = null;
		
		if(array != null) {
			imageList = new ArrayList<Map<String,Object>>();
			Map<String,Object> map;
			for (int i = 0; i < array.length; i++) {
				map = new HashMap<String,Object>();
				map.put("imgUrl_low", array[i].imgUrl_low);
				map.put("imgUrl_standard", array[i].imgUrl_standard);
				map.put("imgUrl_thumbnail", array[i].imgUrl_thumbnail);
				map.put("time", array[i].time);
				map.put("type", array[i].type);
				map.put("caption", array[i].caption);
				map.put("id", array[i].id);
				map.put("username", array[i].username);
				imageList.add(map);
			}
		}
		
		return imageList;
	}
	private static void login2Family()
	{
		new AsyncTask<String, String, String>() {

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				String respon = NetHelper.getResponByHttpClient
				(URL_LOGIN2FAMILY,mUser.username,mUser.id,mToken,mUser.profile_picture);
				return respon;
			}
			
			protected void onPostExecute(String result) {
				callBack.onReturn(result);
			};
		}.execute("");
	}
		
	public class MyOnClickListener implements OnClickListener{
		public Context mContext;
		public WebView mWebView;
		public MyOnClickListener(){};
		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
				if (which == DialogInterface.BUTTON_POSITIVE) {
					cleanCache(mContext);
					mWebView.loadDataWithBaseURL(null, "","text/html", "utf-8",null); 
					callBack.clearCache();
					loginInstagram(mContext, mWebView,callBack);
				}else{
					return;
				}
		}
	};
		

//		public void setContext(Context pContext)
//		{
//			mContext = pContext;
//		}
//		public void setContext(WebView pWebView)
//		{
//			mWebView = pWebView;
//		}
	public static WebViewClient client = new WebViewClient(){
		
		int count = 0;
//		boolean flag = false;
		boolean isLoginSucess = false;
		
		// 点击链接继续在当前browser中响应，而不是新开Android的系统browser中响应该链接
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		};
		
		public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
			System.out.println(host);
			System.out.println(realm);
		};
		public void onFormResubmission(WebView view, android.os.Message dontResend, android.os.Message resend) {
			System.out.println(resend.toString());
		};
		
		public void onPageFinished(WebView view, String url) {
			if( isLoginSucess )
			{
				return;
			}
			System.out.println("finish---" + url);
			count ++ ;
			if (count == 2) {
				count = 0;
				callBack.dismiss();
			}
			int pos;
			pos = url.indexOf("token=");
			if( pos != -1 ){
				isLoginSucess = true;
				mToken = url.substring(pos+6);
				new AsyncTask<String, String, String>() {
					
					@Override
					protected void onPreExecute() {
						callBack.show();
					}

					@Override
					protected String doInBackground(String... params) {
						// TODO Auto-generated method stub
						String respon = NetHelper.getResponByHttpClient(URL_USERINFO + mToken);
						return respon;
					}
					
					protected void onPostExecute(String result) {
						onReturn(result);
					};
				}.execute("");
			}
		};
		
	};
	static class UserInfo{
		String id;
		String username;
		String full_name;
		String profile_picture;
		String bio;
		String website;
		String counts_media;
		String counts_follows;
		String counts_followed_by;
	}
	
	
}
